const { exec } = require('child_process')
const cmd = require('node-cmd')
const express = require('express')
const bodyParser = require('body-parser')
const logger = require('./logs/logger')
const iconv = require('iconv-lite')
const axios = require('axios')
const app = express()


let off
iconv.skipDecodeWarning = true;
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

//域控后端传回接口
app.post('/DomainPort',(req, res) => {
    logger.info(req.body)
    let copyData = req.body
    let threeData = req.body

    axiosPostDomain(threeData)
        setTimeout(() => {
            if(copyData.type == 'add') {
                findOu(req.body,req.body,copyData,res,off)
            }else {
                findUserOuDel(copyData,res,off)
            }
        }, 1500);
    axiosPostAsset(threeData)
    
})

app.listen(5222, () => {
    console.log('HTTP服务端启动,端口为5222')
})


//传给3楼域控和综管资产接口
function axiosPostDomain(data) {
    axios.post('http://www.baidu.com', {data})//填自己的url
        .then((res) => {
            off = res.data
            logs("来自三楼的回应",res.data)
        })
        .catch((err) => {})
}

function axiosPostAsset(data) {
    axios.post('http://www.baidu.com', {data})//填自己的url
        .then((res) => {
            logs("来自综管资产接口回应" + res.data)
        })
        .catch((err) => {
            logs("来自综管资产接口错误" + err)
        })
}
//查找账号所在的组织单位,没有查询到不执行操作，查询到就删除(新的删除方法)
function findUserOuDel(data,res,off) {
    exec(`dsquery user -name ${data.name}`, { encoding: 'buffer' }, (err, stdout) => {
        let circulation = iconv.decode(stdout, 'cp936').replace(/[\r\n]/g,"")
        if(circulation.length < 1) {
            logs(`来自五楼删除信息:${data.name} | 此账号没有查询到或者已经删除成功`)
            if(off.code == 1007) {
                res.send(returnData("删除","success1000",'',off,1000))
            }else {
                res.send(returnData("删除","success1003",'',off,1003))
            }   
        }else {
            exec(`dsrm ${circulation} -noprompt -c`, { encoding: 'buffer' }, (err, stdout) => {
              if(err){
                logs(err)
                if(off.code == 1007) {
                    res.send(returnData("删除","err1005",err,off,1005))
                }else {
                    res.send(returnData("删除","err1008",err,off,1008))
                } 
              }else {
                let circulationData1 = iconv.decode(stdout, 'cp936')
                logs("五楼删除信息：" + circulationData1) 
                res.send(returnData("删除","success1000",'',off,1000))
              }
            })
        }
    })
  }

//查找目录里是否存在该组织单位，未找到和查找失败会新建组织单位
function findOu(data,data2,data3,data4,off) {
    cmd.run(`dsquery ou ${ouFiltrateThree(data2)},DC=knownsec,DC=com`,
    function(err,tempData){
        if(err) {
            logs("未找到三级组织单位或查找失败","正在尝试新建三级组织单位")
            addOuThree(data2,data3,data4,off)
        }else {
            logs("已找到三级组织","单位")
            cmd.run(`dsquery ou ${ouFiltrate(data)},DC=knownsec,DC=com`,
            function(err,tempData){
                if(err) {
                    logs("未找到四级组织单位或查找失败","正在尝试新建四级组织单位")
                    addOu(data,data3,data4,off)
                }else {
                    logs("已找到四级组织","单位")
                    addUser(data3,data4,off)
                }    
            })
        }    
    })
   
}

//创建四级组织单位并创建域账号
function addOu(data,data3,data4,off) {
    cmd.run(`dsadd ou ${ouFiltrate(data)},DC=knownsec,DC=com`,
    function(err,tempdata){
        if(err) {
            logs("创建四级组织单位失败:",err)
        }else {
            logs("创建四级组织单位","成功")
            addUser(data3,data4,off)
        }     
    })
}

//创建三级组织单位并查询是否满足创建四级单位的条件，如果满足即会递归创建四级单位。
function addOuThree(data,data3,data4,off) {
    cmd.run(`dsadd ou ${ouFiltrateThree(data)},DC=knownsec,DC=com`,
    function(err,tempdata){
        if(err) {
            logs("创建三级组织单位失败:",err)
        }else {
            logs("创建三级组织单位","成功")
            addOu(data,data3,data4,off)
        }    
    })
}

//用/分隔出部门名称并返回一个数组
function groupFiltrate(data) {
    data.department = data.department.split("/")
    return data
} 


//传入接收到的数据返回添加完OU字段的字符串，反序数组为创建账号使用(返回值为反序的OU字符串)
function ouFiltrate(data) {
    let temp
    if(typeof(data.department) == 'string'){
        temp = groupFiltrate(data)
    }else {
        temp = data
    }
    let tempArr = []
    for(let i = 1; i < 4;i++){
        tempArr[i-1] = 'ou=' + temp.department[i]
    }
    tempString = tempArr.reverse().join()
    return tempString
}

//临时bug解决(后续可根据返回部门数组的长度进行判断)
function ouFiltrateThree(data) {
    let temp
    if(typeof(data.department) == 'string'){
        temp = groupFiltrate(data)
    }else {
        temp = data
    }
    let tempArr = []
    for(let i = 1; i < 3;i++){
        tempArr[i-1] = 'ou=' + temp.department[i]
    }
    tempString = tempArr.reverse().join()
    return tempString
}
//创建账号方法
function addUser(data,res,off) {
    cmd.run(`dsadd user cn=${data.name},${ouFiltrate(data)},dc=knownsec,dc=com -samid ${data.user} -display ${data.name}  -upn ${data.user}@knownsec.com -pwd ${data.password} -disabled no -mustchpwd yes`,
        function(err,tempdata){
            if(err) {
                logs("五楼添加域账号失败:",err)
                if(off.code == 1005) {
                    res.send(returnData("创建","err1005",err,off,1005))
                }else {
                    res.send(returnData("创建","err1008",err,off,1008))
                }
                
            }else {
                logs("五楼添加域账号","成功")
                if(off.code == 1005) {
                    res.send(returnData("创建","success1000",'',off,1000))
                }else {
                    res.send(returnData("创建","success1003",'',off,1003))
                }
                
            }      
        }
)
}

//日志
function logs(str,data) {
    logger.info(str,data)
}

//返回接口的数据方法
function returnData(dataHeader,type,err,threeData,code){
    const oneSuccessReturn = {
            "code":code,
            "message": dataHeader + "三楼和五楼域账号成功",
    }

    const oneErrReturn = {
            "code":code,
            "message": dataHeader + "五楼域账号失败," + dataHeader + "三楼域账号成功",
            "err":err
    }
    const doubleSuccessReturn = {
            "code":code,
            "message": dataHeader + "五楼域账号成功," + dataHeader + "三楼域账号失败",
            "err":err
    }

    const doubleErrReturn = {
            "code":code,
            "message": dataHeader + "三楼和五楼域账号失败",
            "err":err
    }
    switch(type) {
        case "success1000":
           return oneSuccessReturn
        case "success1003":
           return doubleSuccessReturn
        case "err1005":
           return oneErrReturn
        default:
           return doubleErrReturn
   } 
}

